/*
 * CellSelectionListener.java
 */

package org.owasp.scrubbr.db.report;

import org.owasp.scrubbr.db.Tuple;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


public class CellSelectionListener implements ListSelectionListener {
    
    JTable t;
    JTextArea original;
    JTextArea cleaned;
    JPanel details;
    JButton fix;
    JButton markClean;
    JButton whyFlagged;
    
    
    public CellSelectionListener(JTable table, JTextArea original, JTextArea cleaned, JPanel details, JButton fix, JButton markClean, JButton whyFlagged) {
        this.t = table;             
        this.original = original;
        this.cleaned = cleaned;
        this.details = details;
        this.fix = fix;
        this.markClean = markClean;
        this.whyFlagged = whyFlagged;
    }

    public void valueChanged(ListSelectionEvent event) {
        // See if this is a valid table selection
        if( event.getFirstIndex() >= 0 && t.getSelectedRow() >= 0 && t.getSelectedColumn() >= 0 )
        {
            
            // Get the data model for this table
            DBTableModel model = (DBTableModel)t.getModel();

            // Determine the selected item
            Tuple tuple = model.getTable().getTaintedRows().get(t.getSelectedRow()).getAllTuples().get(t.convertColumnIndexToModel(t.getSelectedColumn()));
                    
            details.setBorder(javax.swing.BorderFactory.createTitledBorder("Details for \"" + tuple.getName() + "\""));
            
            if ( tuple.isTainted() ) {
                String originalValue = tuple.getValue();
                String cleanedValue = tuple.getCleanedValue();

                original.setBackground(Color.WHITE);
                original.setEnabled(true);
                cleaned.setEnabled(true);
                cleaned.setBackground(Color.WHITE);
                fix.setEnabled(true);
                markClean.setEnabled(true);
                whyFlagged.setEnabled(true);
                
                original.setText(originalValue);
                cleaned.setText(cleanedValue);

            } else {
                
                original.setBackground(Color.GRAY);
                original.setText("");
                original.setEnabled(false);
                cleaned.setBackground(Color.GRAY);
                cleaned.setText("");
                cleaned.setEnabled(false);
                fix.setEnabled(false);
                whyFlagged.setEnabled(false);
                
                markClean.setEnabled(false);

            }
        }

    }
    
}
